<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    action="#"
    :before-upload="beforeAvatarUpload"
    accept=".png, .jpg, .jpeg, .gif, .bmp"
    :http-request="handleUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
  import COS from 'cos-js-sdk-v5'
  export default {
    props: {
      value: {
        type: String,
        default: null
      }
    },
    methods: {
      // 上传图片
      handleUpload({ file }) {
        // 创建cos实例
        const cos = new COS({
          SecretId: 'AKIDSggSyHBG5lBnAHwqRvviFZfV5PULmtmy',
          SecretKey: '6wasPhDUXXJ2cy5wNdJyNWP5Wkm3vZy8'
        })
        // 调用uploadFile()上传至腾讯云
        cos.uploadFile({
          Bucket: 'cxk-1305128831',
          Region: 'ap-beijing',
          Key: file.name,
          Body: file
        }, (err, data) => {
          if (err) return this.$message.error(err.message || '上传失败')
          // 成功提示
          this.$message.success('上传成功')
          // 子传父(成功的图片地址带给父组件)，拼接https协议头
          this.$emit('input', `https://${data.Location}`)
        })
      },
      // 上传前的校验
      beforeAvatarUpload(file) {
        // file: 选中的图片文件对象
        // 类型校验通过accept属性完成
        // 校验图片大小，不能超过5M
        const isLt5M = file.size / 1024 / 1024 < 5

        if (!isLt5M) {
          this.$message.warning('图片大小不超过5M')
          // 不通过
          return false
        }
        // 通过了
        return true
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
